from django.http import JsonResponse
from django.contrib.auth import login
from django.contrib.auth.models import User
from game.models.player.player import Player

def register(request):
    data = request.GET
    username = data.get('username',"").strip()
    password = data.get('password',"").strip()
    password_confirm = data.get("password_confirm","").strip()
    if not username or not password :
        return JsonResponse({
                'result':'用户名或密码为空',
                'code':500,
            })
    if password != password_confirm :
        return JsonResponse({
                'result':'两次密码不一致',
                'code':500,
                })
    if User.objects.filter(username=username).exists():
        return JsonResponse({
            'result':'用户已存在',
            'code':304,
            })
    user= User(username=username)
    user.set_password(password)
    user.save()
    Player.objects.create(user=user, photo="https://cloud-minapp-39228.cloud.ifanrusercontent.com/1nIQjmVaIcmts6OT.png")
    login(request,user)
    return JsonResponse({
            'result': 'success',
            'code':200
        })
